/**
 * 本文件定义一些生成图片通用的方法
 */

// 绘制一个带边框的背景，一般用于图片的主要区域背景
export function drawBgBorder(context, x, y, bgwidth, bgheight, opts) {
  // 绘制主要区域的背景
  // 定义圆角矩形的参数
  const x22 = x;
  const y22 = y;
  const width = bgwidth;
  const height = bgheight;
  const radius = opts.radius || 10; // 圆角的大小
  const borderWidth = opts.borderWidth || 2; // 边框宽度
  const startColor = opts.startColor || "#fff"; // 边框宽度
  const endColor = opts.endColor || "#fff"; // 边框宽度
  const borderColor = opts.borderColor || "#eee"; // 边框宽度

  // 创建一个渐变
  const gradient = context.createLinearGradient(x22, y22, x22, y22 + height);
  gradient.addColorStop(0, startColor); // 起始颜色
  gradient.addColorStop(1, endColor); // 结束颜色

  // 设置边框样式
  context.lineWidth = borderWidth;
  context.strokeStyle = borderColor; // 边框颜色

  // 开始绘制边框路径
  context.beginPath();
  context.moveTo(x22 + radius, y22);
  context.arcTo(x22 + width, y22, x22 + width, y22 + radius, radius);
  context.lineTo(x22 + width, y22 + height - radius);
  context.arcTo(
    x22 + width,
    y22 + height,
    x22 + width - radius,
    y22 + height,
    radius
  );
  context.lineTo(x22 + radius, y22 + height);
  context.arcTo(x22, y22 + height, x22, y22 + radius, radius);
  context.lineTo(x22, y22 + borderWidth); // 修正起始点以闭合路径（由于边框宽度）
  context.closePath();

  // 绘制边框
  context.stroke();

  // 填充内部区域（稍微调整以避免边框重叠）
  context.beginPath();
  context.moveTo(x22 + radius + borderWidth / 2, y22 + borderWidth / 2); // 偏移以匹配边框
  context.arcTo(
    x22 + width - borderWidth / 2,
    y22 + borderWidth / 2,
    x22 + width - borderWidth / 2,
    y22 + radius + borderWidth / 2,
    radius - borderWidth / 2
  );
  context.lineTo(
    x22 + width - borderWidth / 2,
    y22 + height - radius - borderWidth / 2
  );
  context.arcTo(
    x22 + width - borderWidth / 2,
    y22 + height - borderWidth / 2,
    x22 + width - radius - borderWidth / 2,
    y22 + height - borderWidth / 2,
    radius - borderWidth / 2
  );
  context.lineTo(
    x22 + radius + borderWidth / 2,
    y22 + height - borderWidth / 2
  );
  context.arcTo(
    x22 + borderWidth / 2,
    y22 + height - borderWidth / 2,
    x22 + borderWidth / 2,
    y22 + radius + borderWidth / 2,
    radius - borderWidth / 2
  );
  context.lineTo(x22 + borderWidth / 2, y22 + borderWidth / 2);
  context.closePath();

  // 设置填充样式为渐变
  context.fillStyle = gradient;

  // 填充内部区域
  context.fill();
}
// 加载图片
export function getURLBase64(url) {
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.open("get", url, true);
    xhr.responseType = "blob";
    xhr.onload = function () {
      if (this.status === 200) {
        var blob = this.response;
        var fileReader = new FileReader();
        fileReader.onloadend = function (e) {
          var result = e.target.result;
          resolve(result);
        };
        fileReader.readAsDataURL(blob);
      }
    };
    xhr.onerror = function (err) {
      reject(err);
    };
    xhr.send();
  });
}

// 加载图片并创建图片实例 
export function getURLBase64Image(url) {
  // ////console.log("%c Line:105 🥤 加载图片并创建图片实例url", "color:#2eafb0", url);
  return new Promise((resolve, reject) => {
    var xhr = new XMLHttpRequest();
    xhr.open("get", url, true);
    xhr.responseType = "blob";
    xhr.onload = function () {
      if (this.status === 200) {
        var blob = this.response;
        var fileReader = new FileReader();
        fileReader.onloadend = function (e) {
          if (e.target.result) {
            var result = e.target.result;
            const image = new Image();
            image.src = result;
            image.onload = () => {
              resolve(image);
            };
          } else {
            reject("图片地址错误");
          }
        };
        fileReader.readAsDataURL(blob);
      }
    };
    xhr.onerror = function (err) {
      reject(err);
    };
    xhr.send();
  });
}

// 批量加载图片新
export async function loadImages(list, length, sign) {
  return new Promise(async (resolve, reject) => {
    if (list.length == 0) {
      reject(false);
    } else {
      let num = length
        ? length > list.length
          ? list.length
          : length
        : list.length;
      let imgs = [];
      let signImg;

      for (let i = 0; i < list.length; i++) {
        let file = list[i];
        if (file.imgUrl) {
          // console.log("%c Line:163 🍕 file", "color:#fca650", file.imgUrl);
          // console.log("%c Line:163 🍕 file.kz1", "color:#fca650", file.kz1);
          let kz1 = "";
          let lv = "";
          let kz2 = "";
          try {
            let image = await getURLBase64Image(file.imgUrl);
            // console.log("%c Line:169 🍑 image", "color:#42b983", image);

            // if (typeof Number(file.kz1) === 'number' && isFinite(Number(file.kz1))) {
            //   lv = file.kz1;
            // } else {

            //   kz1 = await getURLBase64Image(file.kz1);
            // }
            // if (sign&&(file.sort||file.sort==0)) {
            //   signImg = await getURLBase64Image(
            //     " https://game.ikbh.top/makeImg/skinSigns/sign" + file.sort + ".png"
            //   );
            // }
            // if(file.kz2){
            //   kz2 = file.kz2
            // }
            // console.log("%c Line:172 🍔 lv", "color:#2eafb0", lv);
            // 图片实例化成功后存起来
            imgs.push({
              image: image,
              name: file.fieldName,
              sort: file.sort,
              // sign: signImg,
              // kz1: kz1,
              // lv: lv,
              // kz2:kz2
            });
            if (imgs.length >= num) {
              return resolve(imgs);
            }
          } catch (err) {
            console.log("%c Line:81 🍰 err", "color:#33a5ff", err);
            continue;
          }
        }
      }
      resolve(imgs);
    }
  });
}

// 绘制图片 绘制一个区域的多张图片  单页 可带边框 可带名称  可带标签  带标签时一定要加载好标签图片在imgs里面
export function drawImagesArea(context, imgs, options) {
  // startX,startY,rowNum,borderImg,imgWidth1,imgHeight,stepY,stepX
  if (imgs && imgs.length) {
    ////console.log("%c Line:590 🍕 imgs", "color:#f5ce50", imgs);
    let i = 0;
    let line = 1;
    let startX = options.startX;
    let startY = options.startY;
    let hideTxt = options.hideTxt || false;
    let isSign = options.isSign || false;
    let stepY = options.stepY || 80;
    let stepX = options.stepX || 40;
    let txtLineHeight = options.txtLineHeight || 50;
    let borderImg = options.borderImg || "";
    let imgWidth = options.imgWidth1 || 222;
    let height = options.imgHeight || 300;
    let y = startY + height + txtLineHeight;
    let imgy = startY;
    let textColor = options.textColor || "#fff";
    imgs.forEach((item) => {
      if ((i + 1) % (options.rowNum + 1) == 0) {
        imgy = imgy + stepY + height + txtLineHeight;
        y = imgy + height + txtLineHeight;
        line++;
        i = 0;
      }
      // 保持宽高比
      // const originalWidth = item.image.naturalWidth;
      // const originalHeight = item.image.naturalHeight;
      // const targetWidth = imgWidth;
      // const targetHeight = targetWidth * (originalHeight / originalWidth);
      context.drawImage(
        item.image,
        startX + (imgWidth + stepX) * i,
        imgy,
        imgWidth,
        height
      );
      if (borderImg) {
        context.drawImage(
          borderImg,
          startX + (imgWidth + stepX) * i - 8,
          imgy - 8,
          imgWidth + 16,
          height + 16
        );
      }
      if (isSign && item.sign) {
        // 皮肤标签
        context.drawImage(
          item.sign,
          startX + (imgWidth + stepX) * i + imgWidth - 50,
          imgy,
          50,
          50
        );
      }
      if (item.kz1) {
        // 皮肤标签
        context.drawImage(
          item.kz1,
          startX + (imgWidth + stepX) * i + (imgWidth - 150) / 2,
          imgy + height - 80,
          150,
          60
        );
      }
      //  if(item.lv){
      //   context.fillText(item.lv, startX + (imgWidth + stepX) * i, imgy+20);
      // }
      if (!hideTxt) {
        context.fillText(item.name, startX + (imgWidth + stepX) * i, y);
      }
      i++;
    });
    return context;
  } else {
    return context;
  }
}

// 带皮肤背景图 绘制图片 绘制一个区域的多张图片  单页 可带名称  cf 和平
export function drawImagesAreaBg(context, imgs, options) {
  // startX,startY,rowNum,borderImg,imgWidth1,imgHeight,stepY,stepX
  if (imgs && imgs.length) {
    ////console.log("%c Line:590 🍕 imgs", "color:#f5ce50", imgs);
    let i = 0;
    let line = 1;
    let startX = options.startX;
    let startY = options.startY;
    let hideTxt = options.hideTxt || false;
    let defaultSkinbg = options.defaultSkinbg || false;
    let stepY = options.stepY || 80;
    let stepX = options.stepX || 40;
    let txtLineHeight = options.txtLineHeight || 50;
    let txtInside = options.txtInside || false;
    let imgWidth = options.imgWidth1 || 222;
    let height = options.imgHeight || 300;
    let bgImgs = options.bgImgs || [];
    let gameId = options.gameId || '';
    let y = startY + height + txtLineHeight / 2;

    let round = options.round || 10;
    if (txtInside) {
      y = startY + height;
    }
    let imgy = startY;
    imgs.forEach((item) => {
      if ((i + 1) % (options.rowNum + 1) == 0) {
        if (txtInside) {
          imgy = imgy + stepY + height;
          y = imgy + height;
        } else {
          imgy = imgy + stepY + height + txtLineHeight;
          y = imgy + height + txtLineHeight / 2;
        }

        line++;
        i = 0;
      }
      // 保持宽高比
      // const originalWidth = item.image.naturalWidth;
      // const originalHeight = item.image.naturalHeight;
      // const targetWidth = imgWidth;
      // const targetHeight = targetWidth * (originalHeight / originalWidth);
      if (txtInside) {
        context.drawImage(
          item.image,
          startX + (imgWidth + stepX) * i + 3,
          imgy + 3,
          imgWidth - 6,
          height - 70
        );
      } else {
        context.drawImage(
          item.image,
          startX + (imgWidth + stepX) * i + 15,
          imgy + 15,
          imgWidth - 30,
          height - 30
        );
      }
      // 绘制背景图
      if (defaultSkinbg) {
        // console.log('defaultSkinbg: ', defaultSkinbg);
        if (txtInside) {
          context.fillStyle = "#fff";
        } else {
          context.fillStyle = "#fff";
        }
        context.drawImage(
          defaultSkinbg,
          startX + (imgWidth + stepX) * i,
          imgy,
          imgWidth,
          height
        );
      }
      //  if(item.lv){
      //   context.fillText(item.lv, startX + (imgWidth + stepX) * i, imgy+20);
      // }
      if (!hideTxt) {
        if (txtInside) {
          let name1 = item.name
          let name2 = ''
          //  // 设置文字阴影的颜色为黑色
          context.shadowColor = "#000";
          // 轻微模糊阴影
          context.shadowBlur = 3;
          context.shadowOffsetY = 2

          if (item.name.length > 8) {
            name1 = item.name.substr(0, 8)
            name2 = item.name.substr(8)
            context.fillText(
              name1,
              startX + (imgWidth + stepX) * i + 7,
              y - txtLineHeight * 2
            );
            context.fillText(
              name2,
              startX + (imgWidth + stepX) * i + 7,
              y - txtLineHeight + 7
            );
            // strokeText
            // context.strokeText(
            //   name1,
            //   startX + (imgWidth + stepX) * i + 7,
            //   y - txtLineHeight*2
            // );
            // context.strokeText(
            //   name2,
            //   startX + (imgWidth + stepX) * i + 7,
            //   y - txtLineHeight+7
            // );
          } else {
            context.fillText(
              name1,
              startX + (imgWidth + stepX) * i + 7,
              y - txtLineHeight - 5
            );

            // context.strokeText(
            //   name1,
            //   startX + (imgWidth + stepX) * i + 7,
            //   y - txtLineHeight-5
            // );
          }
           //  // 设置文字阴影的颜色为黑色
           context.shadowColor = "none";
           // 轻微模糊阴影
           context.shadowBlur = 0;
           context.shadowOffsetY = 0
        } else {
          context.fillText(
            item.name,
            startX + (imgWidth + stepX) * i + 15,
            y + 13
          );
        }
      }
      // // 右上角等级
      // if(gameId==2&&item.kz2){
      //   context.fillStyle = "#333";
      //   context.fillText(
      //     item.kz2+'级',
      //     startX + (imgWidth + stepX) * i + imgWidth -50,
      //     imgy+30
      //   );

      // }
      i++;
    });
    return context;
  } else {
    return context;
  }
}
